const request = require('superagent');
let dayjs = require('dayjs');

// Cron定时任务插件
let cron = require('node-cron');

// 时区插件
let moment = require('moment-timezone');

let pers= ['王瑞康-康忠礼','蒋凤萍-史小畅','宋明-赵士普','张志鹏-韦亚宁','肖胜特-张冲']

// 新消息通知机器人
let DING_NEWMSG_TOKEN = "https://oapi.dingtalk.com/robot/send?access_token=5a16b5e34b41f2fbead797609580c3ee02774f22c9cdb487125b44d3432e3a8b";

function getDiffDate(targetDate) {
    let date1 = new Date(targetDate);
    let date2 = new Date();
    date1 = new Date(date1.getFullYear(), date1.getMonth(), date1.getDate());
    date2 = new Date(date2.getFullYear(), date2.getMonth(), date2.getDate());
    const diff = date2.getTime() - date1.getTime();
    const diffDate = diff / (24 * 60 * 60 * 1000);
    return diffDate;
}

function deliveryPeople(){
    let param = 0
    let diffNum = getDiffDate('2021/6/15') + param 
    let index = diffNum % pers.length
    console.log(diffNum, index, pers[index])
    return pers[index]
}


// 获取当前时间
function nowTime() {
    // return moment.tz(dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss").toString(), "America/New_York").format("YYYY-MM-DD HH:mm:ss");
    return moment(dayjs(new Date()).format("YYYY-MM-DD HH:mm:ss")).tz("Asia/Shanghai").format("YYYY-MM-DD HH:mm:ss");
}

// 钉钉消息推送
function sendDingMsg(text, token, desp) {
    let sendMsg;
    if (token == DING_NEWMSG_TOKEN) {
        sendMsg = "今天值日生: " + text +  " " + nowTime();
    } else {
        sendMsg = "衡水人才网刷新" + text + "错误信息内容为：" + desp;
    }
    request
        .post(token)
        .set('Content-Type', 'application/json')
        .send({
            "msgtype": "text",
            "text": {"content": sendMsg},
            "at" : {
                "atMobiles ": [
                    ""
                ],
                "isAtAll ": false
            }})
        .then(res => {
            if (res.statusCode == "200") {
                console.log(nowTime() + " ===> 钉钉通知成功！");
            } else {
                console.log(nowTime() + " ===> 钉钉通知失败！");
            }
        });
}

// 新消息在钉钉群里通知
function getNewMsg(msgTxt) {
    sendDingMsg(msgTxt, DING_NEWMSG_TOKEN);
}
// 错误消息发送给钉钉机器人
function serverMsg(text, desp) {
    sendDingMsg(text, DING_ERR_TOKEN, desp);
}


//getNewMsg(deliveryPeople())

console.log(deliveryPeople())
// cron.schedule('0 */1 * * * * *', () => {
cron.schedule('0 0 18 * * * *', () => {
    console.log('刷新程序准备执行 ====>', nowTime());
    getNewMsg(deliveryPeople())
}, {
    scheduled: true,
    timezone: "Asia/Shanghai"
});
